define(['moment', 'JDA'], function (moment, JDA) {
    return ['$scope', '$rootScope', '$mdDialog', 'MMWService', '$filter', '$stateParams', '$timeout', 'config', 'RouterExtendProvider',
        function ($scope, $rootScope, $mdDialog, $MMWService, $filter, $stateParams, $timeout, config, $RouterExtendProvider) {

            $scope.init = function(){
                init();
                $RouterExtendProvider.MailStart();
            };

            // 取得Menu每一列最大格數
            function getMaxColCount(menu){
                var menuCount = 0;
                menu.forEach(function(item){
                    if(item.isShow){
                        menuCount += menuBlockSize(item);
                    }
                });

                var maxColCount = 1;
                if(menuCount > 3){
                    for(var col = 2; col < menuCount; col++){
                        var rowCount = Math.ceil(menuCount / col);
                        if(rowCount <= (col + 1)){
                            maxColCount = col;
                            break;
                        }
                    }
                }
                return maxColCount;
            }

            // 取得子Menu每一列最大格數
            function getChildMaxColCount(menu){
                var menuCount = 0;
                menu.forEach(function(item){
                    if(item.isShow){
                        menuCount += menuBlockSize(item);
                    }
                });

                var maxColCount = 1;
                if(menuCount > 1){
                    maxColCount = 3;
                }
                return maxColCount;
            }

            // Menu占用格數
            function menuBlockSize(menuItem){
                if(menuItem.child){
                    var showChild = $filter('filter')(menuItem.child, {isShow: true}, true);
                    return showChild.length;
                } else {
                    return menuItem.blockSize;
                }
            }

            // 是否有子Menu
            $scope.hasMenuChild = function(menuItem){
                if(menuItem.child){
                    return 'has-child';
                } else {
                    return '';
                }
            };

            $scope.menuStyle = function(menuItem){
                var maxColCount = getMaxColCount($scope.menu);
                var scaleX = Math.ceil(100 / maxColCount);
                var sideLength = (scaleX - ( 1 * maxColCount)) * menuBlockSize(menuItem);
                var display = (sideLength > 0) ? 'flex' : 'none';
                var style = {
                    //'flex': sideLength +'%',
                    //'height': ($scope.hasMenuChild(menuItem))? 'auto' : (((sideLength-2) < 42) ? (sideLength-2) : 42) + 'vw',
                    'display': display
                };
                if($scope.hasMenuChild(menuItem) == 'has-child'){
                    style['color'] = menuItem.color;
                    menuItem.maxColCount = getChildMaxColCount(menuItem.child);
                } else {
                    style['background'] = 'linear-gradient(115deg,' + menuItem.color + '28%, rgba(26, 183, 204, 0) 200%)';
                }
                return style;
            };

            $scope.menuChildStyle = function(menuItem, maxColCount){
                var scaleX = Math.ceil((100 - 4) / maxColCount);
                var sideLength = (scaleX - ( 1 * maxColCount));
                var display = (sideLength > 0) ? 'flex' : 'none';
                var style = {
                    'background': 'linear-gradient(115deg,' + menuItem.color + '28%, rgba(26, 183, 204, 0) 200%)',
                    'flex': sideLength +'%',
                    'height': '30vw',
                    'display': display
                };
                return style;
            };
            $scope.back = function(){
                $scope.$root.showConfirm($filter('translate')('menu.msg.is_logout'),function(dialog){
                    dialog.hide();
                    $timeout(function(){
                        logout(function(){
                            if(config.authorizationmode == 1){
                                JDA.closeWindow(); //關閉目前視窗
                            } else {
                                $rootScope.changeProgram('login',{data:{notLogin:true}}, true);
                            }
                        });
                    });
                });
            };

            $scope.setting = function(){
                //$rootScope.changeProgram('setting',{parent:'menu'});
                $RouterExtendProvider.triggerSetting();
            };

            $scope.changeMachine = function(){
                $rootScope.changeProgram('mobile00',{data:{parent:'menu', select_machines:$scope.machines}});
            };

            $scope.moduleClick = function(moduleItem){
                $scope.$root.subMenu = moduleItem;
            }

            $scope.menuClick = function(menuItem){
                $rootScope.changeProgram(menuItem.name, {data: {parent:'menu', machines:$scope.machines, machines_length:$scope.machines.length}});
            };

            function checkPermissions(menu, permissions){
                //20200616 add by Oliver for 嚴謹比對權限。
                menu.forEach(function(menuItem){
                    var _count = 0;
                    menuItem.child.forEach(function(menueChildItem){
                        var _child_count = 0;
                        menueChildItem.child.forEach(function(menueGrandsonItem){
                            if(menueGrandsonItem.permission && menueGrandsonItem.permission!==''){//如果permission不為空，則判斷permission。
                                if(permissions.indexOf(menueGrandsonItem.permission)!==-1 ){
                                    menueGrandsonItem.isShow=true && menueGrandsonItem.isShow;
                                }else{
                                    menueGrandsonItem.isShow=false;
                                }
                            }else{//如果permission為空，則判斷name。
                                if(permissions.indexOf(menueGrandsonItem.name)!==-1 ){
                                    menueGrandsonItem.isShow=true && menueGrandsonItem.isShow;
                                }else{
                                    menueGrandsonItem.isShow=false;
                                }
                            }
                            if(menueGrandsonItem.isShow)
                                _child_count++;
                        });
                        if(_child_count > 0)
                            menueChildItem.isShow = true;
                        else
                            menueChildItem.isShow = false;

                        if(menueChildItem.isShow)
                            _count++;
                    });

                    if(_count > 0)
                        menuItem.isShow = true;
                    else
                        menuItem.isShow = false;

                    $scope.isShowMenu = $scope.menu.filter(function(item){
                        return item.isShow === true;
                    })
                });
            }

            function init(){
                $scope.machines = [];
                $scope.onwork_time = config.cache.onwork_time = '08:15';
                $scope.menu = angular.merge([], config.menu);
                // 20230303 modify by Alan for#: module_setting卡控
                if(config.cache.module_setting) {
                    $scope.menu = menuParser($scope.menu)
                }
                // 20200617 add by Oliver for 松泓上線
                if(config.cache.permissions){//permissions有內容時就開啟檢查。
                    checkPermissions($scope.menu, config.cache.permissions);
                }else{//permissions是undefined時就要全開權限。
                    $scope.menu.forEach(function(item){
                        item.isShow=true;
                    })
                    $scope.isShowMenu = $scope.menu;
                }
                if($scope.$root.subMenu == undefined)
                    if($scope.menu && $scope.menu.length>0)
                        $scope.$root.subMenu = $scope.menu[0];
            }
            
            // 20230303 modify by Alan for#: module_setting卡控
            // 解析menu轉為前端格式
            function menuParser(source) {
                source.forEach(element => {
                    if(element.child && element.child.length > 0) {
                        menuParser(element.child);
                    } else {
                        element.isShow = checkModuleSetting(element);
                    }
                });
                return source;
            }

            function checkModuleSetting(program) {
                var permissonMap = {
                    'mobile03': config.cache.module_setting.PTC_FLI,
                    'mobile04': config.cache.module_setting.PTC_FLI,
                    'mobile08': config.cache.module_setting.EQP_MNG,
                    "mobileOPM01": config.cache.module_setting.OPM_MNG
                }
                if(permissonMap.hasOwnProperty(program.name)) {
                    return permissonMap[program.name]
                } else {
                    return program.isShow;
                }
            }

            function logout(callback){
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_SYS.clear_login_info_json',
                    content : {},
                    msg : 'menu.msg.logouting',
                    success : function(data){
                        if(callback)
                            callback(data);
                    }
                });
            }

            $MMWService.needLogout = function(callback){
                //20181213 add by Dustdusk for M#53378: 當自動登出時要關閉所有開窗
                $mdDialog.closeAll(function(){
                    $rootScope.showAlert($filter('translate')('error.sessionTimeout'));
                    $rootScope.changeProgram("login", true);
                    if(callback){
                        callback();
                    }
                });
            };
        }
    ];
});
